﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;
using System.IO;
using System.Text;

namespace SlamCms.SharePoint
{
    public partial class SlamCmsFileUpload : LayoutsPageBase
    {
		protected void Page_Load(object sender, EventArgs e)
		{
			// Check to see whether there are uploaded files to process them
			if (Request.Files.Count > 0)
			{

				HttpPostedFile fileUpload = Request.Files[0];
				byte[] content = new byte[fileUpload.InputStream.Length];
				fileUpload.InputStream.Read(content, 0, content.Length);

				// Get POST parameters
				string name = Request["name"] != null ? Request["name"] : string.Empty;
				string fileName = Request["name"] != null ? Request["name"] : string.Empty;
				string uniqueName = Request["uniqueName"] != null ? Request["uniqueName"] : string.Empty;
				string libraryID = Request["libraryID"] != null ? Request["libraryID"] : string.Empty;
				string subFolder = Request["subFolder"] != null ? Request["subFolder"] : string.Empty;
				// The unique name not contains the extension, is just a GUID, so it is needed to add it.
				if (!String.IsNullOrEmpty(uniqueName))
				{
					fileName = uniqueName + Path.GetExtension(name);
				}

				var library = GetDocumentLibrary(libraryID);

				if (library != null)
				{
					library.ParentWeb.AllowUnsafeUpdates = true;
					// If the files must be added on a subfolder, it is created and then the file is uploaded.
					SPFolder folder = null;
					if (!String.IsNullOrEmpty(subFolder))
						folder = library.RootFolder.SubFolders.Add(subFolder.Replace("/", String.Empty));
					else
						folder = library.RootFolder;

					folder.Files.Add(fileName.Substring(fileName.LastIndexOf('/') + 1), content, true);
					library.ParentWeb.AllowUnsafeUpdates = false;
				}
			}
		}


        private SPList GetDocumentLibrary(string listId)
        {
            SPWeb site = this.Web;
            SPList documentList = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite elevatedSite = new SPSite(site.Site.ID))
                {
					foreach (SPWeb elevatedWeb in elevatedSite.AllWebs)
					{
						try
						{
							documentList = elevatedWeb.Lists.GetList(new Guid(listId), false);
						}
						catch { }
						elevatedWeb.Dispose();
					}
                }
            });

            return documentList;
        }
    }
}
